package hoowin.basic.dao.springImp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;

import hoowin.basic.dao.IUserDao;
import hoowin.basic.model.App;
import hoowin.basic.model.User;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class UserDao extends JdbcDaoSupport implements IUserDao {

	@Override
	public User getUserById(int id) {
		if(id<=0)return null;
		String sql = "select * from basic_users where id="+id;
		return (User)super.getJdbcTemplate().queryForObject(sql, new UserRowMapper());
	}
	
	class UserRowMapper implements RowMapper<Object>{
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setAvatar(rs.getString("avatar"));
			App app = new App();
			app.setName(rs.getString("default_app"));
			user.setDefaultApp(app);
			user.setGender(rs.getString("gender"));
			user.setLocale(new Locale(rs.getString("locale")));
			user.setName(rs.getString("name"));
			user.setWords(rs.getString("words"));
			user.setParentId(rs.getInt("parent"));
			return user;
		}	
	}

	@Override
	public boolean addUser(int id, String name, String sex, String locale,
			int parent) {
		String sql = "insert into basic_users (id, name, gender, locale, default_app, parent) values (?, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, id, name, sex, locale, "wsnd", parent )>0){
			return true;
		}else return false;
	}

	@Override
	public boolean updateWords(String words, int userId) {
		String sql = "update basic_users set words='"+words+"' where id="+userId;
		if(super.getJdbcTemplate().update(sql)>0)return true;
		return false;
	}

	@Override
	public boolean updateAvatar(String avatar, int userId) {
		String sql = "update basic_users set avatar='"+avatar+"' where id="+userId;
		if(super.getJdbcTemplate().update(sql)>0)return true;
		return false;
	}
}
